import React, { useRef, useEffect, useState, forwardRef, useImperativeHandle } from 'react';
import MapboxDraw from '@mapbox/mapbox-gl-draw';
import DrawAssistedRectangle from '@geostarters/mapbox-gl-draw-rectangle-assisted-mode';
import classNames from 'classnames/bind';
import { addLineLayer } from 'src/utils/mapFactory';
import IconUtil from './IconUtil';
import dragCircle from './dragCircle';
import styled from './index.less';

const classes = classNames.bind(styled);

const geometryTypeList = [
  {
    drawType: 'draw_circle',
    name: '圆',
    descript: '单击任一点确定圆心后，拖拽绘制圆形',
  },
  {
    drawType: 'draw_rectangle',
    name: '矩形',
    descript: '单击任两点确定宽度后，拖拽绘制矩形',
  },
  {
    drawType: 'draw_polygon',
    name: '多边形',
    descript: '单击任一点开始，形成闭环后结束绘制自定义图形',
  },
];

export default forwardRef((props, ref) => {
  const {
    justMap: { map },
    activeBefore,
    handleDrawEvent,
    insideStyle,
  } = props;
  if (!map) return null;

  const [selectType, setSelectType] = useState('');
  const drawIns = useRef();

  // 框选更新函数
  function update() {
    const features = drawIns.current.getAll();
    handleDrawEvent &&
      handleDrawEvent({
        features,
        remove: () => {
          drawIns.current.deleteAll();
        },
      });
  }
  // 关闭框选
  function closeDraw() {
    map.removeControl(drawIns.current);
  }

  // 处理框选逻辑
  function handleFrame(drawType) {
    if (selectType === drawType) {
      setSelectType('');
    } else {
      drawIns.current.changeMode(drawType, { initialRadiusInKm: 0 });
      setSelectType(drawType);
    }
  }

  // 工具按钮
  function changeDrawMode(drawType) {
    addLineLayer(map).remove();
    activeBefore && activeBefore();
    drawIns.current.deleteAll();
    handleFrame(drawType);
  }

  useEffect(() => {
    drawIns.current = new MapboxDraw({
      modes: Object.assign(MapboxDraw.modes, {
        draw_rectangle: DrawAssistedRectangle,
        draw_circle: dragCircle,
      }),
      displayControlsDefault: false,
      userProperties: true,
    });
    map.addControl(drawIns.current);
    map.on('draw.create', update);
    map.on('draw.delete', update);
    map.on('draw.update', update);
    return () => {
      setSelectType('');
      map.off('draw.create', update);
      map.off('draw.delete', update);
      map.off('draw.update', update);
      if (drawIns.current) {
        closeDraw();
      }
    };
  }, []);

  useImperativeHandle(ref, () => ({
    // 重置工具按钮状态
    resetButStatus: () => {
      drawIns.current && drawIns.current.deleteAll();
      setSelectType('');
    },
  }));

  return (
    <ul className={styled['button-box']}>
      {geometryTypeList.map((g) => {
        const { drawType } = g;
        return (
          <li
            className={classes(selectType === drawType ? 'li-active' : '')}
            onClick={() => {
              changeDrawMode(drawType);
            }}
          >
            <IconUtil insideStyle={insideStyle} className={classes('tools-icon')} drawType={drawType} selectType={selectType}></IconUtil>
          </li>
        );
      })}
    </ul>
  );
});
